import axios from "axios";
import { showNotify } from 'vant';
import 'vant/es/notify/style' 
import userStore from "@/stores/modules/user"
import { removeParameterFromUrl } from '@/utils/util'

window._CONFIG = {}
if (process.env.NODE_ENV == 'test') {
    window._CONFIG['domianURL'] = 'http://121.40.198.1:9999'
    window._CONFIG['jumpOtherURL'] = 'http://112.124.53.62:3001' //系统顶部跳转测试地址
  } else if (process.env.NODE_ENV == 'development') {
    window._CONFIG['domianURL'] = 'http://121.40.198.1:9999' //新版测试
    // window._CONFIG['jumpOtherURL'] = 'http://112.124.53.62:3001' //系统顶部跳转测试地址
    window._CONFIG['jumpOtherURL'] = 'http://192.168.5.198:3000' //系统顶部跳转测试地址
  } else {
    window._CONFIG['domianURL'] = 'http://112.124.64.153:9999' //新正式
    window._CONFIG['jumpOtherURL'] = 'http://121.199.26.74:3000' //系统顶部跳转正式地址
  }
  if (process.env.VUE_APP_FLAG == 'testbuild') {
    window._CONFIG['domianURL'] = 'http://121.40.198.1:9999' //新版测试
    window._CONFIG['jumpOtherURL'] = 'http://112.124.53.62:3001' //系统顶部跳转测试地址
  }
  
  window._CONFIG['casPrefixUrl'] = 'http://cas.example.org:8443/cas'
  window._CONFIG['onlinePreviewDomainURL'] = 'http://fileview.jeecg.com/onlinePreview'
  window._CONFIG['staticDomainURL'] = window._CONFIG['domianURL'] + '/sys/common/static'
  window._CONFIG['pdfDomainURL'] = window._CONFIG['domianURL'] + '/sys/common/pdf/pdfPreviewIframe'
  let apiBaseUrl = window._CONFIG['domianURL'] || '/servicebio'
  // console.log("apiBaseUrl= ",apiBaseUrl)

  // 创建 axios 实例
const service = axios.create({
    //baseURL: '/servicebio',
    baseURL: apiBaseUrl, // api base_url
    timeout: 3600000, // 请求超时时间ms
  })

const err = async error => {
    error.config && removePending(error.config)
    if (error.response) {
      // debugger
      let data = error.response.data
      // const token = Vue.ls.get(ACCESS_TOKEN)
      // console.log('------异常响应------', token)
      console.log('------异常响应------', error.response.status)
      switch (error.response.status) {
        case 403:
          showNotify({ type: 'danger', message: '拒绝访问' });
          break
        case 500:
          //notification.error({ message: '系统提示', description:'Token失效，请重新登录!',duration: 4})
          if (!(data.message == 'Token失效，请重新登录')) {
            // update-begin- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式，不直接跳转----
            // store.dispatch('Logout').then(() => {
            //     window.location.reload()
            // })
  
            // Modal.error({
            //   title: '登录已过期',
            //   content: '很抱歉，登录已过期，请重新登录',
            //   okText: '重新登录',
            //   mask: false,
            //   onOk: () => {
            //     store.dispatch('Logout').then(() => {
            //       Vue.ls.remove(ACCESS_TOKEN)
            //       //window.location.reload()
            //     })
            //   }
            // })
            //notification.error({ message: '系统提示', description: '登录已过期，需要重新登录',duration: 4})
            //Vue.ls.remove(ACCESS_TOKEN)
            // update-end- --- author:scott ------ date:20190225 ---- for:Token失效采用弹框模式，不直接跳转----
            showNotify({ type: 'danger', message: '请求失败' });
          }
          break
        case 404:
          showNotify({ type: 'danger', message: '很抱歉，资源未找到!' });

          break
        case 504:
          showNotify({ type: 'danger', message: '网络超时!' });
          
          break
        case 401:
          showNotify({ type: 'danger', message: '未授权，请重新登录!' });
          const user = userStore()
          if (user.token) {
            user.Logout().then(() => {
              setTimeout(() => {
                // window.location.reload()
                let newUrl = removeParameterFromUrl(window.location.href, 'token')
                window.location.href = newUrl
              }, 1500)
            })
          }
          break
        default:
          showNotify({ type: 'danger', message: data.message });

          break
      }
    }
    return Promise.reject(error)
  }

// request interceptor
service.interceptors.request.use(
  (config) => {
    removePending(config)
    const user = userStore()
    if (user.token) {
      config.headers['X-Access-Token'] = user.token // 让每个请求携带自定义 token 请根据实际情况自行修改
    }
    // 如果repeatRequest不配置，那么默认该请求就取消重复接口请求
    !config.repeatRequest && addPending(config)
    return config
  },
  (error) => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)
  
// response interceptor
service.interceptors.response.use(
  // response => response,
  /**
   * 下面的注释为通过response自定义code来标示请求状态，当code返回如下情况为权限有问题，登出并返回到登录页
   * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
   */
  (response) => {
    // 已完成请求的删除请求中数组
    removePending(response.config)
    return response.data
  },err)

const pendingMap = new Map()
  /**
   * 生成每个请求唯一的键
   * @param {*} config
   * @returns string
   */
  function getPendingKey(config) {
    const { url, method, params } = config
    let { data } = config
    if (typeof data === 'string') data = JSON.parse(data) // response里面返回的config.data是个字符串对象
    return [url, method, JSON.stringify(params), JSON.stringify(data)].join('&')
  }
  
  /**
   * 储存每个请求唯一值, 也就是cancel()方法, 用于取消请求
   * @param {*} config
   */
  function addPending(config) {
    const pendingKey = getPendingKey(config)
    config.cancelToken =
      config.cancelToken ||
      new axios.CancelToken((cancel) => {
        if (!pendingMap.has(pendingKey)) {
          pendingMap.set(pendingKey, cancel)
        }
      })
  }
  /**
   * 删除重复的请求
   * @param {*} config
   */
  function removePending(config) {
    const pendingKey = getPendingKey(config)
    if (pendingMap.has(pendingKey)) {
      const cancelToken = pendingMap.get(pendingKey)
      cancelToken(pendingKey)
      pendingMap.delete(pendingKey)
    }
  }

export default service